// subpkg_backstage/pages/backstage.js
const db = wx.cloud.database()
const todos = db.collection('orders_data')
const innerAudioContext = wx.createInnerAudioContext({
  useWebAudioImplement: false
})
innerAudioContext.src = 'cloud://ax-cloud-6gs71h36ef44f6e6.6178-ax-cloud-6gs71h36ef44f6e6-1311849331/a20240109/新的订单.mp3'

const state = ['un_finish', 'in_finish', 'finish', 'cancel']

Page({
  // 切换状态
  switchTab(e){
    const idx = e.currentTarget.dataset.idx
    this.setData({ 
      actIndex: idx,
      skipNum: 0,
      orderData: []
     })
    if(idx === 0) this.getOrderData(state[idx], false)
    if(idx === 1) this.getOrderData(state[idx], true)
    if(idx === 2) this.getOrderData(state[idx], true)
    if(idx === 3) this.getOrderData(state[idx], true)
  },
  // 展开信息订单信息
  showOrderInfo(e){
    const idx = e.currentTarget.dataset.index
    let newStatusList = [...this.data.itemShowState]
    newStatusList[idx] = !newStatusList[idx]
    this.setData({
      itemShowState: newStatusList
    })
  },
  // 接单
  switchState(e){
    wx.showModal({
      title: '提示',
      content: `是否确定${e.currentTarget.dataset.txt}订单？`,
      complete: (res) => {
        if (res.confirm) {
          const id = e.currentTarget.dataset.id
          const state = e.currentTarget.dataset.state
          wx.cloud.callFunction({
            name: 'set_order_state',
            data: {
              id,
              state: state
            }
          }).then(res => {
            let data = this.data.orderData
            data = data.filter(obj => obj._id != id)
            this.setData({ orderData: data })
          })
        }
      }
    })
  },
  // 获取订单数据
  async getOrderData(val, real){
    await wx.showLoading({
      title: '获取中',
    })
    // 获取数据总条数
    const totalNum = await todos.where({ orderState: val }).count()
    console.log(totalNum.total);
    let options1 = {
      state: val,
      skipNum: 0,
      perNum: totalNum.total,
      isUser: false
    }
    if(real){
      options1 = {
        state: val,
        skipNum: this.data.skipNum,
        perNum: this.data.perNum,
        isUser: false
      }
      // 是否已到最后一页
      if(this.data.skipNum >= totalNum.total){
        wx.showToast({
          title: '没有更多了',
          icon: 'none'
        })
        return
      }
    }
    
    // 请求订单数据
    const res = await wx.cloud.callFunction({
      name: 'get_user_order',
      data: options1
    })
    let newData = res.result.data.reverse()
    let options2 = { 
      orderData: newData,
      itemShowState: newData.map(() => false)
     }
    // 保存请求的数据
    if(real){
      newData = this.data.orderData
      newData.push(...res.result.data.reverse())
      options2 = { 
        orderData: newData,
        itemShowState: newData.map(() => false),
        skipNum: this.data.skipNum + this.data.perNum
       }
    }
    // 修改对应内容
    this.setData(options2)
    await wx.hideLoading()
  },
  // 实时数据更新
  realData(){
    const watcher = db.collection('orders_data')
    watcher
    .where({
      orderState: 'un_finish'
    })
    .watch({
      onChange: (snapshot) => {
        // 获取新增的数据
        snapshot.docChanges.forEach(async change => {
          // 判断类型是否为新增
          if(change.dataType === 'add'){
            // 播放提示音
            innerAudioContext.play()
            this.getOrderData('un_finish', false)
            this.setData({ actIndex: 0 })
            wx.showModal({
              title: '提示',
              content: '您有新的订单！',
              showCancel: false,
            })
          }
        })
      },
      onError(err) {
        console.error('监听失败', err);
        wx.showModal({
          title: '警告',
          content: '订单获取失败，请重新进入订单管理页',
          showCancel: false
        })  
      }
    })
  },
  
  /**
   * 页面的初始数据
   */
  data: {
    actIndex: 0,
    orderData: [], // 订单数据
    itemShowState: [], // 控制每个订单信息的显示隐藏
    perNum: 10, //
    skipNum: 0, //
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.getOrderData('un_finish')
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {
    this.realData()
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {
    
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {
    if(this.data.actIndex != 0){
      this.getOrderData(state[this.data.actIndex], true)
    }
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})